#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <error.h>
#include <stdio.h>
#include <sys/epoll.h>
#include <unistd.h>

#include "../ftp.h"

#define ARGS_CHECK(argc,expect){if(argc!=expect){printf("ARGC NUM IS WRONG!\n");exit(-1);}}

int tcp_init(const char *ip,const char *port);

int main(int argc, char *argv[])
{
    // ./server 192.168.159.128 12345 a
    ARGS_CHECK(argc,4);

    int sockfd;
    if((sockfd=tcp_init(argv[1],argv[2]))==-1){fprintf(stderr,"tcp init occur error\n");return -1;}
    
    int clientfd;
    if((clientfd=accept(sockfd,NULL,NULL))==-1){perror("accept");return -1;};

    printf("clientfd=%d\n",clientfd);

    if(send_file(clientfd,argv[3])==-1){perror("send_file");close(clientfd);return -1;}

    return 0;
}


int tcp_init(const char *ip,const char *port){
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd==-1){
        perror("socket");
        return -1;
    }

    int flag;
    socklen_t optlen=sizeof(flag);
    if(getsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,&optlen)==-1){
        perror("getsockopt");
        return -1;
    }
    flag=1;
    if(setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,optlen)==-1){
        perror("setsockopt");
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=inet_addr(ip);
    addr.sin_port=htons(atoi(port));
    if(bind(sockfd,(struct sockaddr*)&addr,sizeof(addr))==-1){
        perror("bind");
        return -1;
    }

    if(listen(sockfd,10)==-1){
        perror("listen");
        return -1;
    }

    return sockfd;
}
